<template>
    <div>
    <!-- <el-row class="bgW">
        <el-col :span="22">
            <el-form class="search" label-suffix="：" :inline="true" size="mini" :model="search">
                <el-form-item label="排班月份">
                    <el-date-picker
                        v-model="search.create_time_start"
                        type="date"
                        class="w130"
                        placeholder="排班月份"
                        value-format="yyyy-MM"
                    ></el-date-picker>
                    
                </el-form-item>
            </el-form>
        </el-col>
        <el-col :span="2" style="text-align: right;">
            <el-button type="primary" icon="el-icon-search" size="mini" @click="">搜索</el-button>
        </el-col>
    </el-row> -->
    <el-row>
        <el-col :span="24">
            <el-table
                :data="list"
                size="big"
                border
                :cell-style="$style.cellStyle"
                :header-cell-style="$style.rowClass"
            >
                
                <ElTableColumn label="员工姓名" width="150" prop="name"  fixed="left"/>
    
                <ElTableColumn v-for="item in workDate" :label="item" width="80">
                    <template slot-scope="{ row }" >
                        <div
                            class="hand hand-color1"
                            @click="clickGrids(row.id,row.year,item,row[item])"
                            v-if="row[item] == 0"
                        >休</div>
    
                        <div
                            class="hand hand-color2"
                            @click="clickGrids(row.id,row.year,item,row[item])"
                            v-else-if="row[item] == 1"
                        >全天班</div>
    
                        <div
                            class="hand hand-color3"
                            @click="clickGrids(row.id,row.year,item,row[item])"
                            v-else-if="row[item] == 2"
                        >上午班</div>
    
                        <div
                            class="hand hand-color4"
                            @click="clickGrids(row.id,row.year,item,row[item])"
                            v-else
                        >下午班</div>
                    </template>
                </ElTableColumn>
    
                <ElTableColumn  label="一键排班" fixed="right" width="120">
                  <template slot-scope="{ row }">
                    <span class="theme"
                    @click="setScheduleWeekSave(row.id)"
                    >一键排班</span>
                  </template>
                </ElTableColumn>
                <ElTableColumn  label="操作" fixed="right" width="120">
                  <template slot-scope="{ row }">
                    <span class="theme"
                    @click="tapBtn('update', row.id)"
                    >编辑排班</span>
                  </template>
                </ElTableColumn>
            </el-table>
        </el-col>
    </el-row>
  <el-dialog title="编辑排班" :visible.sync="dialogVisible" width="40%">
      <el-form :model="selectDate" label-width="150px">
        <el-form-item label="日期" >
          <el-input v-model="selectDate.date" placeholder="" autocomplete="off" readonly></el-input>
        </el-form-item>
        <el-form-item label="排班类型" >
          <el-select v-model="selectDate.workType" placeholder="请选择排班类型" @change="onWorkTypeChange">
            <el-option
              v-for="item in selectDate.workTypeList"
              :key="item.workType"
              :label="item.text"
              :value="item.workType"
            >
            </el-option>
          </el-select>
        </el-form-item>
         <!-- 
    可预约时间      "kk_time": 0,   0没有设置   1已设置
    已预约时间      "yy_time": 0,   0没有预约   1已预约   2已被重复预约
    重复预约时间    "dd_time":0,    0没有设置   1已设置
    -->
        <!-- 可预约时间段选择 -->
        <el-form-item label="可预约时间段" v-if="selectDate.workType > 0">
          <div class="time_div">
            <div v-for="item in getAvailableTimeSlots" 
                 :key="item.showTime" 
                 :class="{
                   'time-disabled': item.yy_time !== 0,
                   'time-available': item.kk_time === 1 && item.yy_time === 0,
                 }"
                 @click="handleAppointmentClick(item)">
              {{item.showTime}}
              <br>{{ item.yy_time !== 0 ? '已被预约' : '' }}
            </div>
          </div>
        </el-form-item>

        <!-- 可重复预约时间段选择 -->
        <el-form-item label="可重复预约时间段" v-if="selectDate.workType > 0">
          <div class="time_div">
            <div v-for="item in getAvailableTimeSlots" 
                 :key="item.showTime" 
                 :class="{
                   'time-disabled': item.yy_time === 2,
                   'time-repeat-available': item.dd_time === 1 && item.yy_time !== 2,
                 }"
                 @click="handleRepeatClick(item)">
                {{item.showTime}}
               <br>{{ item.yy_time == 2 ? '已被重复预约' : '' }}
            </div>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="scheduleSave">保存</el-button>
      </div>
    </el-dialog>
    </div>
    
    </template>
    
    <script>
    import { mapGetters } from 'vuex'
    import { staffList, getShopBusinessTime,scheduleList, getMonth, setSchedule , setScheduleWeek } from "@/api/staff";
    class Options {
        nurse_id = [];
    }
    
    export default {
        name: 'StaffSchedule',
        data() {
            return {
                options: new Options(), // 选项
                workDate: new Date(),
                appointTime:[], // 点击可预约时间段
                repeatTime:[],// 点击可重复预约时间段
                resData: [],
                list: [],
                $workDate: [],
                amList: [],
                pmList: [],
                full_dayList: [],
                dialogVisible:false,
                selectDate:{
                    date:'',
                    workType:'',
                    id:'',
                    shopId: '',
                    workTypeList:[
                            {
                                workType:'0',
                                text:"休"
                            },
                            {
                                workType:'1',
                                text:"全天班"
                            },
                            {
                                workType:'2',
                                text:"上午班"
                            },
                            {
                                workType:'3',
                                text:"下午班"
                            }
                        ]
                },
            }
        },
        computed: {
            ...mapGetters(['userInfo']),
              // 根据排班类型获取可用时间段
            getAvailableTimeSlots() {
                switch (this.selectDate.workType) {
                    case '1': // 全天班
                    return this.full_dayList;
                    case '2': // 上午班
                    return this.amList;
                    case '3': // 下午班
                    return this.pmList;
                    default:
                    return [];
                }
            },
        },
        watch: {},
    
        mounted() {
            //console.log(this.userInfo.shop_id);
            this.getStaffList();
            this.getMonDate();
            
        },
    
        methods: {
                    // 处理可预约时间段点击
            handleAppointmentClick(item) {
            console.log(item)

            // 如果时段不可预约，不执行任何操作
                if (item.yy_time !== 0) return;
                const timeKey = item.showTime;
                if(item.kk_time === 1){
                    item.kk_time = 0;
                    this.appointTime = this.appointTime.filter(
                        time => time !== timeKey
                        );
                }else if(item.kk_time === 0){
                    item.kk_time = 1;
                    this.appointTime.push(item.showTime)
                }
            },
            
            // 处理可重复预约时间段点击
            handleRepeatClick(item) {
            console.log(item)
            // 如果时段不可重复预约，不执行任何操作
                if (item.yy_time === 2) return;
                const timeKey = item.showTime;
                if(item.dd_time === 1){
                    item.dd_time = 0;
                    this.repeatTime = this.repeatTime.filter(
                        time => time !== timeKey
                    );
                    console.log(  this.repeatTime ,"  this.repeatTime ")

                }else if(item.dd_time === 0){
                    item.dd_time = 1;
                    this.repeatTime.push(item.showTime)
                }
            },

            // 获取员工列表
            async getStaffList() {
                staffList({ shopId: this.userInfo.shop_id, page: 1, limit: 1000000 }).then((res) => {
                    this.options.nurse_id = res.list;
    
                    const staffIds = [];
                    let arr = res.list;
    
                    arr.forEach(element => {
                        staffIds.push(element.id);
                    });
                    
                    this.getStaffScheduleList(staffIds);
                    
                });
            },
    
            // 获取当月员工排班列表
            async getStaffScheduleList(staffIds) {
                scheduleList({ staffIds: staffIds }).then((res) => {
                    console.log(res);
    
                    this.list = res.data.data;
                })
               
            },
    
            // 获取当月日期
            async getMonDate() {
                getMonth().then((res) => {
                    console.log(res);
                    this.workDate = res;
                })
            },
    
            onChangeTabs(tab, event){
                console.log(tab.label);
            },
    
            onChangeChecked(e){
                console.log(e);
            },
    
            // 点击单元格进行排班
            async clickGrids(id,year,item,workType){
                await getShopBusinessTime({shop_id: this.userInfo.shop_id, shop_person_id: id, time: (year+'-'+item).replace(/-/g, '')}).then((res) => {
                    this.amList = res.data.am;
                    this.pmList = res.data.pm;
                    this.full_dayList = res.data.day;
                    this.onWorkTypeChange(workType);

                })


                this.dialogVisible = true;
                this.selectDate.date = (year+'-'+item).replace(/-/g, '');
                this.selectDate.workType = workType.toString();

                this.selectDate.id = id;

                // this.dialogVisible=true;
                // this.selectDate.date = year+"-"+item;
                // this.selectDate.workType=workType;
                // this.selectDate.id=id;
                // console.log(this.selectDate);

            },
            // 排班类型变更时
            onWorkTypeChange(e) {
                this.appointTime = [];
                this.repeatTime = [];
                if(e == 1){
                    this.appointTime = this.full_dayList.filter(item => item.kk_time === 1 && item.yy_time === 0).map(item => (item.showTime));
                    this.repeatTime = this.full_dayList.filter(item => item.dd_time === 1 && item.yy_time !== 2).map(item => ( item.showTime));
                }else if(e == 2 ){
                    this.appointTime = this.amList.filter(item => item.kk_time === 1 && item.yy_time === 0).map(item => (item.showTime));
                    this.repeatTime = this.amList.filter(item => item.dd_time === 1 && item.yy_time !== 2).map(item => ( item.showTime));
                }else if(e == 3){
                    this.appointTime = this.pmList.filter(item => item.kk_time === 1 && item.yy_time === 0).map(item => ( item.showTime));
                    this.repeatTime = this.pmList.filter(item => item.dd_time === 1 && item.yy_time !== 2).map(item => (item.showTime));
                }
            
            },
            // 日历
            tapBtn(type, id) {
                switch (type) {
                    case "update":
                    this.$router.push("./updateStaffSchedule?id=" + id+"&shop_id="+this.userInfo.shop_id);
                    break;
                }
            },
            //编辑排班
            scheduleSave(){
                let params = {
                    shop_id:this.userInfo.shop_id,
                    time:this.selectDate.date,
                    shop_person_id:this.selectDate.id,
                    work_type:this.selectDate.workType == 0 || this.selectDate.workType == 1?'0':(this.selectDate.workType-1),
                    is_work:this.selectDate.workType == 0 ?'0':'1',
                    kk_time:this.appointTime,
                    dd_time:this.repeatTime
                }
                setSchedule(params).then((res) => {
                    if(res.code != 200){
                        this.$message({
                            message: res.msg,
                            type: 'warning'
                        });
                    }else{
                        this.$message({
                            message: res.data.msg,
                            type: 'success'
                        });
                    }
                    this.getStaffList();
                    this.getMonDate();
                })
                //console.log(param);
                this.dialogVisible = false;
            },
            //一次排版一周
            setScheduleWeekSave(id){
                setScheduleWeek({
                    shop_id:this.userInfo.shop_id,
                    shop_person_id:id
                }).then((res) => {
                    //console.log(res);
                    if(res.code != 200){
                        this.$message({
                            message: res.msg,
                            type: 'warning'
                        });
                    }else{
                        this.$message({
                            message: '排班成功',
                            type: 'success'
                        });
                    }
                    this.getStaffList();
                    this.getMonDate();
                })
            }
            
        },
    };
    </script>
    <style lang="scss" scoped>

.time_div {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  padding: 8px 0;
  
  div {
    padding: 0 12px;
    border-radius: 4px;
    text-align: center;
    // min-width: 80px;
    transition: all 0.2s;
    cursor: pointer;
    border: 1px solid #EBEEF5;
  }
  
  .time-disabled {
    background-color: #909399;
    color: #fff;
    cursor: not-allowed;
  }
  
  .time-available {
    background-color: #33bea7;
    border: 1px solid #33bea7;
    color: #fff;
    &:hover {
      border-color: #33bea7;
    }
  }
  
  .time-selected {
    background-color: #33bea7;
    color: #fff;
    border-color: #33bea7;
    transform: translateY(-2px);
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  }
  
  .time-repeat-available {
    // background-color: #fff;
    // border: 1px solid #EBEEF5;
    background-color: #33bea7;
    border: 1px solid #33bea7;
    color: #fff;
    &:hover {
      border-color: #2bada8;
    }
  }
  
  .time-repeat-selected {
    background-color: #2bada8;
    color: #fff;
    border-color: #2bada8;
    transform: translateY(-2px);
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  }
}

.hand {
  cursor: pointer;
  padding: 5px;
  border-radius: 4px;
  text-align: center;
}

.hand-color1 { background-color: ForestGreen; color: white; }
.hand-color2 { background-color: #dfe2e9; color: #6b849d; }
.hand-color3 { background-color: #2bada8; color: white; }
.hand-color4 { background-color: #c96bc2; color: white; }

.theme {
  color: #33bea7;
  cursor: pointer;
}
::v-deep .el-input{
    width: 220px !important;
}
</style>